﻿using System;
using LinqToTwitter;
using Microsoft.SystemCenter.Orchestrator.Integration;
using SocialMediaIntegrationPack.Properties;

namespace SocialMediaIntegrationPack
{
    /// <summary>
    /// Base class for all twitter activities
    /// </summary>
    public abstract class TwitterActivity
    {
        /// <summary>
        /// Security configuration for OAuth
        /// </summary>
        [ActivityConfiguration]
        public OAuthConfiguration Configuration { get; set; }

        /// <summary>
        /// Responses of twitter
        /// </summary>
        [ActivityOutput("Twitter Response")]
        public string Response { get; set; }

        /// <summary>
        /// Save exception information to Responses of Activity
        /// </summary>
        /// <param name="exception"></param>
        protected void LogException(Exception exception)
        {
            if (exception.InnerException != null)
            {
                Response = exception.InnerException.Message;
                throw exception.InnerException;
            }

            Response = exception.Message;
        }

        /// <summary>
        /// Perform authorization against twitter.com using Configuration
        /// Then create and return new TwitterContext
        /// </summary>
        protected TwitterContext Authorize()
        {
            var userAuthorizer = Authentication.Authenticate(Configuration.AccessToken, Configuration.AccessTokenSecret);
            if (userAuthorizer == null || !userAuthorizer.IsAuthorized)
            {
                throw new Exception(Resources.UNAUTHORIZED_USER);
            }
            return new TwitterContext(userAuthorizer);
        }

        /// <summary>
        /// Max Length of tweets and direct messages
        /// </summary>
        protected static readonly int STATUS_MAX_LENGTH = 140;
    }
}
